const jwt = require('jsonwebtoken');
const { getNormalConfig } = require('../config/config');
const VAR_SEQUENCE_KEY = getNormalConfig('VAR_SEQUENCE_KEY');
const VAR_SEQUENCE_TIMING = getNormalConfig('VAR_SEQUENCE_TIMING');
const querystring = require('querystring');

//生成token
const generateToken = (payload) => {
  return new Promise(async (resolve, reject) => {
    const token = await jwt.sign(payload, VAR_SEQUENCE_KEY, {
      expiresIn: VAR_SEQUENCE_TIMING,
    });
    resolve(token);
  });
};
const getUrlParams = (url) => {
  const params = querystring.parse(url.split('?')[1]);
  return params ?? {};
};
const dealResponse = (ctx, res) => {
  if (res.status) {
    ctx.status = 200;
    ctx.body = {
      code: '0000',
      message: '操作成功',
      data: res.result,
    };
  } else {
    ctx.status = 201;
    ctx.body = {
      code: '9999',
      message: String(res.result),
      data: [],
    };
  }
};
module.exports = {
  generateToken,
  getUrlParams,
  dealResponse,
};
